<script lang="ts" setup>
import type { RowType } from './types';

import type { VxeGridProps } from '#/adapter/vxe-table';

import { ref } from 'vue';
import { $t } from '#/locales';
import { Page, useVbenDrawer, useVbenModal } from '@vben/common-ui';
import { useAppConfig } from '@vben/hooks';

import {
  Button,
  Dropdown,
  Menu,
  MenuItem,
  message,
  Modal,
  Popconfirm,
  Space,
  Switch,
} from 'ant-design-vue';
const route = useRoute();
const router = useRouter();
const routeMeta = router.currentRoute.value.meta;
const viewTitle = routeMeta.title.replace('管理', '');
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deleteThemes,
  getThemes,
  getThemesFiles,
  postThemesActive,
  putThemes,
} from '#/api/admin/theme';
import Icon from '#/components/Icons';

import {
  FilesWidgetsConfigDrawerView,
  FrameView,
  OntInstalled,
} from './components';

defineOptions({
  name: 'AdminTheme',
});
const { baseURL } = useAppConfig(import.meta.env, import.meta.env.PROD);
const defaultTheme = ref('default');
const gridOptions: VxeGridProps<RowType> = {
  rowConfig: { isCurrent: true, isHover: true },
  pagerConfig: {
    enabled: false,
  },
  columns: [
    { title: $t("page.common.Code"), type: 'seq', width: 50 },
    { field: 'theme', title: $t("admin.Identifier") },
    { field: 'name', title: $t("page.common.Name") },
    { field: 'version', title: $t("admin.Version") },
    { field: 'lang', title: $t("admin.Language") },
    { field: 'author', title: $t("admin.Author") },
    { field: 'description', title: $t("page.common.Description") },
    {
      field: 'status',
      title: $t("page.common.Status") ,
      slots: { default: 'status' },
    },
    {
      slots: { default: 'action' },
      field: 'action',
      fixed: 'right',
      title: $t("page.common.Action") ,
      width: 240,
    },
  ],
  exportConfig: {},
  height: 'auto',
  keepSource: true,
  proxyConfig: {
    ajax: {
      query: async () => {
        const { data } = await getThemes();
        defaultTheme.value = data.default_theme;
        // 查找默认主题的索引
        const defaultThemeIndex = data.list.findIndex(
          (item: RowType) => item.theme === data.default_theme,
        );

        // 如果找到了默认主题，则将该主题的状态设置为 1
        if (defaultThemeIndex !== -1) {
          data.list[defaultThemeIndex].status = 1;
        }
        return data;
      },
    },
  },
  toolbarConfig: {
    custom: true,
    // export: true,
    // import: true,
    refresh: true,
    zoom: true,
  },
};

const [Grid, GridApi] = useVbenVxeGrid({
  gridOptions,
});

const [OntInstalledModal, modalApi] = useVbenModal({
  // 连接抽离的组件
  connectedComponent: OntInstalled,
  onClosed() {
    const modalData = modalApi.getData();
    if (modalData?.isUpdata) {
      GridApi.query();
    }
  },
});

const handleUnInstall = async (row: RowType) => {
  const $table = GridApi.grid;
  if ($table) {
    await deleteThemes(row.theme);
    $table.remove(row);
    message.success(`卸载 ${row.theme} 成功`);
  }
};

const handleUpdate = async (theme: string) => {
  await putThemes(theme);
  message.success(`更新 ${theme} 成功`);
};

const onChange = async (scope: { row: any; rowIndex: number }) => {
  Modal.confirm({
    title: '系统提示',
    content: `确认要${scope.row.status === 0 ? '禁用' : '启用'}${
      scope.row.theme
    }吗?`,
    async onOk() {
      try {
        await postThemesActive(scope.row.theme);
        message.success(
          `已${scope.row.status === 0 ? '禁用' : '启用'}${scope.row.theme}`,
        );
        GridApi.query();
      } catch {
        scope.row.status === 0
          ? (scope.row.status = 1)
          : (scope.row.status = 0);
      }
    },
    onCancel() {
      scope.row.status === 0 ? (scope.row.status = 1) : (scope.row.status = 0);
    },
  });
};

const [FilesWidgetsConfigDrawerl, FilesWidgetsConfigDrawerlApi] = useVbenDrawer(
  {
    // 连接抽离的组件
    connectedComponent: FilesWidgetsConfigDrawerView,
  },
);

const handleFiles = async (theme: string) => {
  const {
    data: { list },
  } = await getThemesFiles(theme);
  FilesWidgetsConfigDrawerlApi.setData({
    theme,
    files: list,
  });
  FilesWidgetsConfigDrawerlApi.open();
};

const [FrameModal, FrameModalApi] = useVbenModal({
  // 连接抽离的组件
  connectedComponent: FrameView,
});

const handleDesign = async (theme: string) => {
  message.loading({
    content: `加载资源中...`,
    duration: 1,
    onClose: () => {
      // 打开模板设计窗口
      FrameModalApi.setState({
        title: `${theme}--模板设计`,
        fullscreen: true,
      });
      FrameModalApi.setData({
        url: baseURL,
        theme,
      });
      FrameModalApi.open();
    },
  });
};
</script>

<template>
  <Page auto-content-height>
    <OntInstalledModal />
    <FilesWidgetsConfigDrawerl />
    <FrameModal />
    <Grid :table-title="viewTitle +' '+$t('page.common.List')">
      <template #toolbar-tools>
        <Button class="mr-2" type="primary" @click="() => modalApi.open()">
          <template #icon>
            <span class="anticon">
              <Icon icon="ri:add-line" />
            </span>
          </template>
          {{$t("admin.Install Template")}}
        </Button>
      </template>
      <template #status="scope">
        <Switch
          v-model:checked="scope.row.status"
          :checked-value="1"
          :disabled="scope.row.theme === defaultTheme"
          :un-checked-value="1"
          :checked-children="$t('admin.Enable')"
          un-checked-children="停用"
          @change="onChange(scope)"
        />
      </template>

      <template #action="{ row }">
        <Space>
          <Button type="primary" @click="handleDesign(row.theme)">
            <template #icon>
              <span class="anticon">
                <Icon icon="ri:brush-line" />
              </span>
            </template>
            {{$t("admin.Design")}}
          </Button>
          <Popconfirm
            :disabled="row.theme === defaultTheme"
            cancel-text="否"
            ok-text="是"
            title="确认卸载？"
            @confirm="handleUnInstall(row)"
          >
            <Button
              :disabled="row.theme === defaultTheme"
              danger
              type="primary"
            >
              <template #icon>
                <span class="anticon">
                  <Icon icon="ri:uninstall-line" />
                </span>
              </template>
              {{$t("admin.Uninstall")}}
            </Button>
          </Popconfirm>
          <Dropdown>
            <Button type="link">
              <template #icon>
                <span class="anticon">
                  <Icon icon="ri:more-fill" />
                </span>
              </template>
            </Button>
            <template #overlay>
              <Menu>
                <MenuItem>
                  <Button type="link" @click="handleFiles(row.theme)">
                    <template #icon>
                      <span class="anticon">
                        <Icon icon="ri:settings-5-line" />
                      </span>
                    </template>
                    {{$t("page.common.Cofig")}}
                  </Button>
                </MenuItem>
                <MenuItem>
                  <Button type="link" @click="handleUpdate(row.theme)">
                    <template #icon>
                      <span class="anticon">
                        <Icon icon="ri:refresh-line" />
                      </span>
                    </template>
                    更新
                  </Button>
                </MenuItem>
              </Menu>
            </template>
          </Dropdown>
        </Space>
      </template>
    </Grid>
  </Page>
</template>
